<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class RankController extends Controller
{
    /**
     * 缓存键名
     */
    const CACHE_KEY = 'rank';

    /**
     * 缓存时间
     */
    const CACHE_TIME = 300;

    /**
     * 缓存人数
     */
    const CACHE_NUMBER = 100;

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        /** @var User $user */
        $user = Auth::user();

        // 我的排行
        $userRank = User::query()->where('score', '>', $user->score)->count() + 1;

        // 如果我在前 100 名，清除缓存
        if ($userRank < self::CACHE_NUMBER) {
            Cache::forget(self::CACHE_KEY);
        }

        // 前 100 名排行，缓存 300 秒
        $rank = Cache::remember(self::CACHE_KEY, self::CACHE_TIME, function () {
            return User::with('weChatUser')
                ->where('score', '>', 0)
                ->orderByDesc('score')
                ->take(self::CACHE_NUMBER)
                ->get();
        });

        return view('h5.rank', compact('user', 'rank', 'userRank'));
    }
}
